<?php
// JoomlaPlugin.php
require_once(KT_LIB_DIR . '/browse/browseutil.inc.php');
require_once(KT_LIB_DIR . '/plugins/plugin.inc.php');
require_once(KT_LIB_DIR . '/plugins/pluginregistry.inc.php');
require_once(KT_LIB_DIR . '/authentication/interceptor.inc.php');
require_once(KT_LIB_DIR . '/authentication/interceptorregistry.inc.php');
require_once "HTTP/Request.php"; //This is from pear. You need to have pear installed.

class JoomlaInterceptor extends KTInterceptor {
	var $sNamespace  = "joomla.joomla.interceptor";

	function authenticated() {
		
		//get config
		$oKTConfig = KTConfig::getSingleton();
		$joomlaURL = $oKTConfig->get('joomlaURL', false);

		//scan the cookies, one of them should have the session id if we are logged in to Joomla
		$req =& new HTTP_Request($joomlaURL . "kt_sso.php");
		foreach ($_COOKIE as $cookie) {
			$req->addQueryString('cookie',$cookie);
			$req->addQueryString('debug', 'true');
			$req->sendRequest();
			$JoomlaUser = $req->getResponseBody();
			if ($JoomlaUser) {  
				break;    //if we found the right cookie, $JoomlaUser holds the user id
			}
		}
		$oUser =& User::getByUsername($JoomlaUser);
		return $oUser;
	}

	function takeover() {
		// If keyless, redirect to Joomla login
		
		//get config
		$oKTConfig = KTConfig::getSingleton();
		$joomlaURL = $oKTConfig->get('joomlaURL', false);
		
		//first ask Joomla for the name of the session cookie
		$req =& new HTTP_Request($joomlaURL . "kt_sso.php");
		$req->addQueryString('action','getCookieName');
		$req->sendRequest();
		$cookieName = $req->getResponseBody();
		if (!isset($_COOKIE[$cookieName])) {
			header("Location: ". $joomlaURL);
			exit();
		}
	}
}

class JoomlaPlugin extends KTPlugin {
	var $sNamespace = "joomla.joomla.plugin";
	var $autoRegister = true;
	var $bAlwaysInclude = true;

	function JoomlaPlugin($sFilename = null) {
		$res = parent::KTPlugin($sFilename);
		$this->sFriendlyName = _kt("Joomla Plugin");
		return $res;
	}

	function setup() {
		$this->registerInterceptor("JoomlaInterceptor", "joomla.joomla.interceptor", __FILE__);
	}
}
$oRegistry =& KTPluginRegistry::getSingleton();
$oRegistry->registerPlugin('JoomlaPlugin','joomla.joomla.plugin', __FILE__);
?>
